import React, { useEffect, useState, useRef } from "react";
import styles from "./index.less";
import { getNewsongs, getTopAlbum } from "@/api";
import { Affix } from 'antd';
import MyImg from '@/components/myimg'
import IconFont from "@/components/iconfont";
import moment from 'moment'
import imgUnload from '@/assets/img/music-unload.png'
import LoadingPage from '@/components/loadingPage'
const Bottompage1: React.FC = () => {
  const newSongstypes = [
    { name: "全部", value: 0 },
    { name: "华语", value: 7 },
    { name: "欧美", value: 96 },
    { name: "韩国", value: 16 },
    { name: "日本", value: 8 }
  ];
  const [songTypeid, setSongTypeid] = useState(0);
  const [newsongs, setNewsongs] = useState([]);
  const [isLoading, setIsLoading] = useState<boolean>(true)

  useEffect(() => {
    setIsLoading(true)
    // console.log('加载')
    getNewsongs({ type: songTypeid }).then((res) => {
      setNewsongs(res.data);
    });
  }, [songTypeid]);
  // useEffect(()=>{
  //   console.log('调用了setState')
  // },[isLoading])
  const getTwonum = (num: number) => {
    return num == 0 ? "00" : num < 10 ? "0" + num : "" + num;
  };
  {
    /* 传入接口返回的对象，提取playtime，返回播放时间的 分（两位）：秒（两位） */
  }
  const getplayTime = (item: any): string => {
    const ms: number =
      item?.bMusic?.playTime
      || item?.hMusic?.playTime
      || item?.mMusic?.playTime
      || item?.lMusic?.playTime
    if (!ms) {
      return "未知"
    };
    return (
      getTwonum(Math.floor(ms / 60000)) +
      ":" +
      getTwonum(Math.round(ms / 1000 - Math.floor(ms / 60000) * 60))
    );
  };
  return (
    <div className={styles["bottompage1"]}>
      <ul className={styles["btns-top"]}>
        <li className={styles["btns-top-left"]}>
          {newSongstypes.map((item: { name: string; value: number }, index: number) => (
            // 判断是否选中来选择格式
            <a
              key={`newSongstypesindex${index}`}
              onClick={() => {
                setSongTypeid(item.value);

              }}
              className={
                item.value === songTypeid
                  ? styles["selected"]
                  : styles["unselected"]
              }
            >
              {item.name}
            </a>
          ))}
        </li>
        <li className={styles["btns-top-right"]}>
          <a className={styles["btn-1"]}>
            <IconFont type='iconbofang' />
            <span
              // onClick={()=>{
              //   setIsLoading(false)
              //   console.log('dian ji')
              // }}
              style={{ marginLeft: '5px' }}
            >
              播放全部
            </span>
          </a>
          <a className={styles["btn-2"]}>
            <IconFont type='iconshoucangjia' />
            <span style={{ marginLeft: '5px' }}>收藏全部</span>
          </a>
        </li>
      </ul>
      <div
        className={styles["context"]}
        onLoad={(ele: any) => {
          ele.stopPropagation()
          setIsLoading(false)
          ele = null
        }}
      >
        {newsongs.map((item: any, index: number) => (
          <div
            key={`newsongsindex${index}`}
            className={styles['ranklist-one']}
          >
            {/* 用两位数表示 */}
            <div className={styles['ranklist-left']}>
              <span className={styles["span1"]}>
                {getTwonum(index + 1)}
              </span>
              <div className={styles["span2"]}>
                <MyImg
                  src={item.album?.blurPicUrl}
                  imgSize={{ width: 140 }}
                  placeholderSrc={imgUnload}
                  loading={'lazy'}
                />
                <span className={styles['icon-bofang']}>
                  <IconFont type='iconziyuan1' />
                </span>
              </div>
              <div className={styles['span3']}>
                <span className={styles["span3-1"]}>
                  {item?.name}
                </span>
                <span className={styles["span3-2"]}>
                  {item?.alias[0]}
                </span>
              </div>
            </div>
            <div className={styles['ranklist-right']}>
              <a className={styles["span4"]}>
                {item?.artists[0]?.name}
              </a>
              <a className={styles["span5"]}>
                <span className={styles["span5-1"]}>
                  {item?.name}
                </span>
                <span className={styles["span5-2"]}>
                  {item?.alias[0]}
                </span>
              </a>
              <span className={styles["span6"]}>
                {getplayTime(item)}
              </span>
            </div>
          </div>
        ))}
      </div>
      <LoadingPage isLoading={isLoading}></LoadingPage>
    </div>
  );
};

const Bottompage2: React.FC<any> = ({ lmParentelement }) => {
  const el = useRef<any>(null)
  const contextWeek = useRef<any>(null)
  const [albumArea, setAlbumArea] = useState<string>('ALL');//带有初始值
  const [albumType, setAlbumType] = useState<string>('new');
  const [albumsWeek, setAlbumsWeek] = useState<Array<object> | null>(null)
  const [albumsMonth, setAlbumsMonth] = useState<Array<object> | null>(null)
  const [isDisplay, setIsDisplay] = useState<boolean>(true)
  const [isLoading, setIsLoading] = useState<boolean>(true)
  const loadOnecCount: number = 24
  let limit: number = 56
  let canRun: boolean = true
  let canRunonly: boolean = true
  const runOnlyFirst = (fun: Function) => {
    if (canRunonly) {
      canRunonly = false
      fun()
    }
  }
  let month: number = Number.parseInt(moment().format('M'))
  let year: number = Number.parseInt(moment().format('YYYY'))
  const nextMonth = (isFinished: boolean) => {
    if (isFinished) {
      if (month = 1) {
        month = 12
        year = year - 1
      } else {
        month = month - 1
      }
      return new Promise((resolve, rejected) => {
        if (month != Number.parseInt(moment().format('M'))) {
          resolve(true)
        } else {
          rejected(new Error('异步未解决'))
        }
      })
    }
  }

  const addLimit = async (tmonth: number, tyear: number) => {
    // console.log('addLimit')
    if (canRun) {
      let isFinished: boolean = false
      canRun = false
      try {
        let limits = limit
        limit = limits + loadOnecCount
        await getTopAlbum({
          area: albumArea,
          type: albumType,
          month: tmonth,
          year: tyear
          // limit:limits
        }).then(res => {
          if (res?.weekData?.length > 0) {
            if (res?.weekData?.length < limit) {
              runOnlyFirst(() => { setAlbumsWeek(res?.weekData) })
              // console.log('weekData已经获取完成:' + (limit - res?.weekData?.length));
              if (res?.monthData?.length > limit) {
                setAlbumsMonth(res?.monthData?.slice(0, limit))
              } else {
                isFinished = true
              }
            } else if (res?.weekData) {
              setAlbumsWeek(res?.weekData.slice(0, limit))
            }
          } else if (res?.monthData?.length > limit) {
            setAlbumsMonth(res?.monthData?.slice(0, limit))
          } else {
            isFinished = true
          }
        })
        // console.log('请求接口成功')
      } catch (er) {
        console.log(er);
      }
      // console.log(month + '' + year)
      await nextMonth(isFinished)?.then((res) => {
        if (res) {
          return setTimeout(() => {
            canRun = true
          }, 200);
        }
      }, err => { console.log(err) })
      return setTimeout(() => {
        canRun = true
      }, 200);
    }
  }
  const newAlbumstypes = {
    'area': [
      { name: "全部", value: 'ALL' },
      { name: "华语", value: 'ZH' },
      { name: "欧美", value: 'EA' },
      { name: "韩国", value: 'KP' },
      { name: "日本", value: 'JP' }
    ], 'type': [
      { name: '全部', value: 'new' },
      { name: '热门', value: 'hot' }
    ]
  };
  const loadingBottom = () => {
    // console.log('gundong')
    if (document.body.offsetHeight
      && (lmParentelement?.scrollTop >
        0.8
        * (
          el?.current?.offsetHeight
          - document.body.offsetHeight
        )
      )) {
      addLimit(month, year)
    }
    if (contextWeek) {
      if (lmParentelement?.scrollTop - contextWeek?.current?.offsetHeight > 0) {
        setIsDisplay(false)
      } else {
        setIsDisplay(true)
      }
    }
  }
  useEffect(() => {
    if (lmParentelement) {
      lmParentelement.addEventListener('scroll', loadingBottom)
    }
    return () => {
      if (lmParentelement) {
        lmParentelement.removeEventListener('scroll', loadingBottom)
      }
    }
  }, [lmParentelement])
  useEffect(() => {
    getTopAlbum({ area: albumArea, type: albumType }).then(res => {
      if (res?.weekData?.length > 0) {
        if (res?.weekData?.length < limit) {
          setAlbumsWeek(res?.weekData)
          setAlbumsMonth(res?.monthData.slice(0, limit - res?.weekData?.length))
        }
        else {
          setAlbumsWeek(res.weekData)
          setAlbumsMonth(null)//变换类型时清除上一个种类的数据
        }
      } else {
        setAlbumsWeek(null)
        setAlbumsMonth(res.monthData.slice(0, limit))
      }
    })
    setIsLoading(true)
    return () => {
      setAlbumsWeek(null)
      setAlbumsMonth(null)//变换类型时清除上一个种类的数据
    }
  }, [albumArea, albumType])
  return (
    <div className={styles["bottompage2"]} ref={el}>
      <ul className={styles["btns-top"]}>
        <li className={styles["btns-top-left"]}>
          {
            newAlbumstypes.area.map((item, index: number) => (
              <a
                key={`newAlbumstypesindex${index}`}
                onClick={() => {
                  setAlbumArea(item.value);
                }}
                className={
                  item.value === albumArea
                    ? styles["selected"]
                    : styles["unselected"]
                }
              >
                {item.name}
              </a>
            ))
          }

        </li>
        <li className={styles["btns-top-right"]}>
          {
            newAlbumstypes.type.map((item, index: number) => (
              <>
              <a
                key={`newAlbumstypes.typeIn${index}`}
                onClick={() => {
                  setAlbumType(item.value);
                }}
                className={
                  item.value === albumType
                    ? styles["selected"]
                    : ''}
              >
                {item.name}
                
              </a>
              <span
                key={`newAlbumstypes.typeInspan${index}`}
              >|</span>
              </>
            ))
          }
        </li>
      </ul>
      <div className={styles["context"]} onLoadCapture={(ele: any) => {
        ele.stopPropagation()
        // console.log(ele)
        setIsLoading(false)
        ele = null
      }}>
        {albumsWeek && albumsWeek.length > 0 && (
          <ul className={styles['context-week']} ref={contextWeek}>
            <Affix target={() => lmParentelement}
              className={styles['floattag1']}
              style={isDisplay ? { display: 'block' } : { display: 'none' }}>
              <p style={{ margin: '0' }}
              >本周</p>
              <p>新碟</p>
            </Affix >
            {
              albumsWeek.map((item: any, index: number) => (
                <li
                  className={styles['one-album']}
                  key={`albumsWeekIn${index}`}
                >
                  <div className={styles['btn-img']}>
                    <div className={styles['shadow-top']}></div>
                    <div className={styles['shadow-bottom']}></div>
                  </div>
                  <div className={styles['img']}>
                    <MyImg
                      src={item?.blurPicUrl}
                      imgSize={{ width: 140 }}
                      placeholderSrc={imgUnload}
                    />
                    <div className={styles['icon-bofang']}>
                      <IconFont type='iconziyuan1' />
                    </div>
                  </div>
                  <a className={styles['a-songname']}>{item?.name}</a>
                  <a className={styles['a-artist']}>{item?.artist?.name}</a>
                </li>
              ))
            }
            <li style={{ clear: 'both' }}></li>
          </ul>
        )
        }
        {
          albumsMonth && albumsMonth.length > 0 && (
            <ul className={styles['context-month']}>
              <Affix target={() => lmParentelement}
                className={styles['floattag2']}>
                <p className={styles['p-month']}>{month > 9 ? `${month}` : `0${month}`}</p>
                <p className={styles['p-year']}>{year}</p>
              </Affix >
              {albumsMonth.map((item: any, index: number) => (
                <li
                  className={styles['one-album']}
                  key={`albumsMonthIn${index}`}
                >
                  <div className={styles['btn-img']}>
                    <div className={styles['shadow-top']}></div>
                    <div className={styles['shadow-bottom']}></div>
                  </div>
                  <div className={styles['img']}>
                    <MyImg
                      loading={'lazy'}
                      src={item?.blurPicUrl}
                      imgSize={{ width: 100 }}
                      placeholderSrc={imgUnload}
                    />
                    <span className={styles['icon-bofang']}>
                      <IconFont type='iconziyuan1' />
                    </span>
                  </div>
                  <a className={styles['a-songname']}>{item?.name}</a>
                  <a className={styles['a-artist']}>{item?.artist?.name}</a>
                </li>
              ))
              }
              <li style={{ clear: 'both' }}></li>
            </ul>
          )
        }
        <li style={{ clear: 'both' }}></li>
      </div>
      <LoadingPage isLoading={isLoading} style={{ color: 'rgb(51,51,51)' }}></LoadingPage>
    </div>
  );
};
interface propTypes {
  parentelement: any
}
const Latest_music: React.FC<propTypes> = ({ parentelement }) => {
  const pageref = useRef(null)
  const [tabName, setTabName] = useState<string>("first")
  return (
    <div ref={pageref} >
      <ul className={styles["topselection"]}>
        <li>
          <input
            type="button"
            value="新歌速递"
            onClick={() => { setTabName("first"); }}
            className={`${`${tabName}` === `${"first"}`
              ? ''
              : `${styles["unselected"]}`
              }`}
          />
          <input
            type="button"
            value="新碟上架"
            onClick={() => { setTabName("second") }}
            className={`${`${tabName}` === `${"second"}`
              ? ''
              : `${styles["unselected"]}`
              }`}
          />
        </li>
      </ul>
      {tabName === "first" ? <Bottompage1 /> : <Bottompage2 lmParentelement={parentelement} />}
    </div>
  );
};
export default Latest_music;
